using System;
using System.Collections.Generic;
using System.Linq;
using RewiredConsts.__Naptime;
using Steamworks;
using UnityEngine;

namespace __Naptime.Steam
{
	public sealed class ResolutionManager : Singleton<ResolutionManager>
	{
		public const string RESOUTION_KEY = "RESOLTION_KEY";

		public const string FULLSCREEN_KEY = "Fullscreen";

		[SerializeField]
		private Resolution[] resolutions;

		private Dictionary<string, Vector2Int> _resolutionNameToResolutionAspect;

		private string _resolutionName;

		public static string DefaultResolutionKey => "1920x1080";

		public IReadOnlyDictionary<string, Vector2Int> ResolutionNameToResolutionAspect => _resolutionNameToResolutionAspect;

		public static event Action OnResolutionChange;

		private void Start()
		{
			QualitySettings.vSyncCount = 1;
			if (_resolutionNameToResolutionAspect == null)
			{
				_resolutionNameToResolutionAspect = resolutions.ToDictionary((Resolution e) => e.resolutionName, (Resolution e) => e.resolutionAspect);
			}
			if (SteamUtils.IsSteamRunningOnSteamDeck())
			{
				SetResolution(new Vector2Int(1280, 800), isSteamDeck: true);
				Screen.fullScreenMode = FullScreenMode.FullScreenWindow;
				Screen.fullScreen = true;
				ResolutionManager.OnResolutionChange?.Invoke();
			}
			else
			{
				string @string = NintendoPlayerPrefs.GetString("RESOLTION_KEY", DefaultResolutionKey);
				Vector2Int resolution = GetResolution(@string);
				SetResolution(resolution);
				bool num = NintendoPlayerPrefs.GetInt("Fullscreen", 1) == 1;
				Screen.fullScreenMode = (num ? FullScreenMode.FullScreenWindow : FullScreenMode.Windowed);
				Screen.fullScreen = num;
			}
		}

		public void SetResolution(Vector2Int size, bool isSteamDeck = false)
		{
			Screen.SetResolution(size.x, size.y, isSteamDeck || NintendoPlayerPrefs.GetInt("Fullscreen", 1) == 1);
			ResolutionManager.OnResolutionChange?.Invoke();
		}

		private void InvokeOnResolutionChange()
		{
			ResolutionManager.OnResolutionChange?.Invoke();
		}

		public Vector2Int GetResolution(string id)
		{
			if (!_resolutionNameToResolutionAspect.TryGetValue(id, out var value))
			{
				return _resolutionNameToResolutionAspect[DefaultResolutionKey];
			}
			return value;
		}

		public string GetNextResolutionKey(string currentKey)
		{
			return _resolutionNameToResolutionAspect.GetNextKey(currentKey);
		}

		public string GetPreviousResolutionKey(string currentKey)
		{
			return _resolutionNameToResolutionAspect.GetNextKey(currentKey);
		}
	}
}
